import { app, BrowserWindow } from 'electron'
import * as path from 'path'
import { format as formatUrl } from 'url'

let mainWin: BrowserWindow | null
// 是否是开发模式
const isDevelopment = process.env.NODE_ENV !== 'production'
// 独占锁检测
function singleInstanceCheck() {
    const lock = app.requestSingleInstanceLock()
    if (!lock) {
        app.quit()
    } else {
        app.on('second-instance', (event: Electron.Event, argv: string[], workingDirectory: string) => {
            if (mainWin && !mainWin.isDestroyed()) {
                if (mainWin.isMaximized()) mainWin.restore()
                mainWin.focus()
            } else {
                createMain()
            }
        })
    }
}
singleInstanceCheck()
/**
 * 创建主窗口
 */
function createMain() {
    mainWin = new BrowserWindow({
        width: 800,
        height: 600,
        webPreferences: {
            nodeIntegration: true,
            webSecurity: !isDevelopment,
            webviewTag: true
        }
    })
    if (isDevelopment) {
        // mainWin.webContents.openDevTools()
        mainWin.loadURL('http://127.0.0.1:8081')
    } else {
        mainWin.loadURL(formatUrl({
            pathname: path.join(__dirname, 'index.html'),
            protocol: 'file',
            slashes: true
        }))
    }
    // main widnow lifecycle
    mainWin.on('close', () => mainWin = null)
    mainWin.webContents.on('devtools-opened', () => {
        mainWin?.focus()
        setImmediate(() => mainWin?.focus())
    })
}
// 🌹 app lifecycle
app.whenReady().then(createMain)
app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') app.quit()
})
app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0 && (!mainWin || mainWin?.isDestroyed())) {
        createMain()
    }
})